// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate
const limit = 20
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let page=event.page
  let prouser =await db.collection('user').aggregate().match({
    history: _.exists(true)
  }).project({
    _id:0,
    _openid:1,
    jonnerName:1,
    image:'$userWxInfo.avatarUrl',
  }).limit(1000).end()

  const users=prouser.list
  let userdict={}
  for(let item of users){
    let key=item._openid
    userdict[key]=item
  }
  let where=event.show?{rankList:_.elemMatch(_.eq(wxContext.OPENID))}:{}
  let prohs=await db.collection('gamehistory').where(where).orderBy('time','desc').skip((page-1)*limit).limit(limit).get()
  const historys=prohs.data
  let hslist=[]
  for(let item of historys){
    let curobj={}
    curobj.creater=userdict[item._openid]
    curobj.time=item.time
    let rl=[]
    for(let oid of item.rankList){
      rl.push(userdict[oid])
    }
    curobj.rl=rl
    hslist.push(curobj)
  }
  return hslist
}